package com.ma.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ma.gulimall.member.dao.MemberDao;
import com.ma.gulimall.member.dao.MemberLevelDao;
import com.ma.gulimall.member.entity.MemberEntity;
import com.ma.gulimall.member.entity.MemberLevelEntity;
import com.ma.gulimall.member.exception.PhoneException;
import com.ma.gulimall.member.exception.UsernameException;
import com.ma.gulimall.member.service.MemberService;
import com.ma.gulimall.member.vo.GiteeUser;
import com.ma.gulimall.member.vo.MemberUserLoginVo;
import com.ma.gulimall.member.vo.MemberUserRegisterVo;
import com.ma.gulimall.member.vo.SocialUser;
import com.ma.gulimall.utils.HttpUtils;
import com.ma.gulimall.utils.PageUtils;
import com.ma.gulimall.utils.Query;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void register(MemberUserRegisterVo vo) {
        MemberEntity memberEntity = new MemberEntity();

        //设置默认等级【普通会员】
        MemberLevelEntity levelEntity = memberLevelDao.getDefaultLevel();
        memberEntity.setLevelId(levelEntity.getId());

        //设置其它的默认信息
        //检查用户名和手机号是否唯一。感知异常，异常机制
        checkPhoneUnique(vo.getPhone());
        checkUserNameUnique(vo.getUserName());

        memberEntity.setNickname(vo.getUserName());
        memberEntity.setUsername(vo.getUserName());
        //密码进行MD5加密 Spring security
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode(vo.getPassword());
        memberEntity.setPassword(encode);
        memberEntity.setMobile(vo.getPhone());
        memberEntity.setGender(0);
        memberEntity.setCreateTime(new Date());

        //保存数据
        baseMapper.insert(memberEntity);
    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneException {
        Integer phoneCount = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (phoneCount > 0) {
            throw new PhoneException();
        }
    }

    @Override
    public void checkUserNameUnique(String userName) throws UsernameException {
        Integer usernameCount = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", userName));
        if (usernameCount > 0) {
            throw new UsernameException();
        }
    }

    /**
     * 本地登录
     * 1、根据网页反馈的用户名/手机号查出用户信息
     * 2、如果不存在该用户，返回失败；
     * 3、存在该用户则进行密码核验
     * 4、密码核验失败，返回失败
     * 5、密码合演成功，返回成功，将用户信息封装到data中反馈给前端
     *
     * @param vo
     * @return
     */
    @Override
    public MemberEntity login(MemberUserLoginVo vo) {
        String loginacct = vo.getLoginacct();
        String password = vo.getPassword();

        //SELECT * FROM `ums_member` WHERE username=? OR mobile =? 可以用用户名或者手机号登录
        MemberEntity memberEntity = baseMapper.selectOne(new QueryWrapper<MemberEntity>()
                .eq("username", loginacct).or().eq("mobile", loginacct));

        if (memberEntity != null) {
            String password1 = memberEntity.getPassword();
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            boolean matches = bCryptPasswordEncoder.matches(password, password1);
            if (matches) {
                memberEntity.setPassword(" ");
                return memberEntity;
            }
        }
        return null;
    }


    /**
     * 社交登录
     *
     * @param socialUser
     * @return
     */
    @Override
    public MemberEntity login(SocialUser socialUser) {
        //具有登录和注册合并逻辑
        String uid = socialUser.getUid();

        //1、判断是否注册登录过
        MemberEntity memberEntity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if (memberEntity != null) {
            //注册过，更新用户访问令牌和过期时间
            MemberEntity update = new MemberEntity();
            update.setId(memberEntity.getId());
            update.setAccessToken(socialUser.getAccess_token());
            update.setExpiresIn(socialUser.getExpires_in());
            baseMapper.updateById(update);

            memberEntity.setAccessToken(socialUser.getAccess_token());
            memberEntity.setExpiresIn(socialUser.getExpires_in());
            return memberEntity;

        } else {
            //2、没有查到当前社交用户的信息对应的记录就得注册一个
            MemberEntity register = new MemberEntity();
            //3、查询当前社交用户的社交账号信息（昵称，性别，邮箱.....）
            try {
                Map<String, String> map = new HashMap<>();
                map.put("access_token", socialUser.getAccess_token());
                HttpResponse response = HttpUtils.doGet("https://gitee.com", "/api/v5/user", "get", new HashMap<>(), map);

                if (response.getStatusLine().getStatusCode() == 200) {
                    //查询成功
                    String json = EntityUtils.toString(response.getEntity());
                    GiteeUser giteeUser = JSON.parseObject(json, GiteeUser.class);
                    register.setUsername(giteeUser.getName());
                    register.setNickname(giteeUser.getName());
                    register.setEmail(giteeUser.getEmail());
                }
            } catch (Exception e) {
            }
            register.setLevelId(1L);
            register.setCreateTime(new Date());
            register.setSocialUid(socialUser.getUid());
            register.setAccessToken(socialUser.getAccess_token());
            register.setExpiresIn(socialUser.getExpires_in());
            //将用户信息存入数据库
            baseMapper.insert(register);
            return register;
        }
    }

}